package com.eight.util;

import com.eight.vo.WeChatComData;
import com.eight.vo.WeChatPay;
import com.github.wxpay.sdk.WXPayUtil;

import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;

/**
 * @Description: 微信支付的工具类
 * @Author: Van.Planifolia
 * @CreateTime: 2023-03-04  14:45
 * @Version: 1.0
 */
public class WeChatPayUtil {
    private static final String appid;
    private static final String mchid;
    private static final String apiKey;

    static {
        // 读取配置文件中的信息
        Properties properties = new Properties();
        try {
            String path = Objects.requireNonNull(WeChatPay.class.getClassLoader().getResource("")).getPath();
            FileReader fileReader = new FileReader(path + "/wechatpay.properties");
            properties.load(fileReader);
            appid = properties.getProperty("weixin.appid");
            mchid = properties.getProperty("weixin.mch_id");
            apiKey = properties.getProperty("weixin.api_key");
            System.out.println(apiKey);
            fileReader.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 生产微信支付二维码的方法
     *
     * @param weChatComData 需要的微信等待对象信息
     * @return 生产的结果
     */
    public synchronized static WeChatComData makePayOrder(WeChatComData weChatComData) {
        // 然后我们就调用微信的sdk来生产二维码信息
        Map<String, String> params = new HashMap<>();
        params.put("appid", appid);
        params.put("mch_id", mchid);
        params.put("nonce_str", WXPayUtil.generateNonceStr());
        // 订单标题
        params.put("body", weChatComData.getSerialNumber());
        // 订单uuid
        params.put("out_trade_no", weChatComData.getSerialNumber());
        // 订单金额
        params.put("total_fee", new BigDecimal("0.01").multiply(new BigDecimal(100)).longValue() + "");
        params.put("spbill_create_ip", "127.0.0.1");//真实服务器的ip
        params.put("notify_url", "http://localhost:8080/pay/back");//支付成功后跳转的路径
        params.put("trade_type", "NATIVE");
        try {
            //2.远程调用微信支付接口
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //设置支持https协议的请求
            httpClient.setHttps(true);
            //设置xml格式的参数
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(params, apiKey));
            //发送请求
            httpClient.post();

            //获取返回的结果
            String content = httpClient.getContent();
            //把xml转化为map
            Map<String, String> map = WXPayUtil.xmlToMap(content);
            if ("SUCCESS".equals(map.get("result_code"))) {
                WeChatComData resultData = new WeChatComData();
                resultData.setAmount(weChatComData.getAmount())
                        .setTitle(weChatComData.getTitle())
                        .setSerialNumber(weChatComData.getSerialNumber())
                        .setCodeUrl(map.get("code_url"));
                return resultData;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 验证订单是否已经支付
     *
     * @param orderNo 订单编号
     * @return 是否成功
     */
    public static boolean queryPayStatus(String orderNo) {
        Map<String, String> params = new HashMap<>();
        params.put("appid", appid);
        params.put("mch_id", mchid);
        params.put("out_trade_no", orderNo);
        params.put("nonce_str", WXPayUtil.generateNonceStr());
        try {
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            httpClient.setHttps(true);
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(params, apiKey));
            httpClient.post();
            String content = httpClient.getContent();
            Map<String, String> map = WXPayUtil.xmlToMap(content);
            return "SUCCESS".equals(map.get("trade_state"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static void main(String[] args) {
        System.out.println(makePayOrder(new WeChatComData().setTitle("?321321").setSerialNumber("piowejqdkjp213932-0djska").setAmount(BigDecimal.valueOf(0.01))));
    }
}
